import signal
import sys
import atexit
from app.utils import setup_logger
from app import create_app
from camera import cleanup
from werkzeug.serving import run_simple
from werkzeug.middleware.proxy_fix import ProxyFix

# 全局日志记录器
logger = None

def signal_handler(signum, frame):
    """信号处理函数"""
    global logger
    if logger is None:
        logger = setup_logger()
    logger.info(f"收到信号 {signum}，准备关闭服务...")
    cleanup()
    sys.exit(0)

if __name__ == '__main__':
    try:
        # 设置日志
        logger = setup_logger()
        
        # 注册信号处理器
        signal.signal(signal.SIGTERM, signal_handler)
        signal.signal(signal.SIGINT, signal_handler)
        
        # 注册退出处理
        atexit.register(cleanup)
        
        # 创建应用
        app = create_app()
        logger.info("服务启动中...")
        
        # 启用热重载，支持远程访问
        app.wsgi_app = ProxyFix(app.wsgi_app)
        run_simple('0.0.0.0', 5000, app,
                  use_reloader=True,
                  use_debugger=True,
                  use_evalex=True,
                  threaded=True)  # 启用多线程支持
            
    except Exception as e:
        if logger is None:
            logger = setup_logger()
        logger.error(f"服务运行出错: {str(e)}")
    finally:
        cleanup()